//
//  BirthViewController.m
//  CoolMove
//
//  Created by CA on 15/4/25.
//  Copyright (c) 2015年 CA. All rights reserved.
//

#import "BirthViewController.h"
#import <DateTools/DateTools.h>


static const NSInteger kYearComponent = 0;
static const NSInteger kMonthComponent = 1;
static const NSInteger kDayComponent = 2;
static const NSInteger kMaxYear = 2020;
static NSString * const kDefalutBirthYear = @"1990";

@interface BirthViewController () <UIPickerViewDataSource, UIPickerViewDelegate, UIGestureRecognizerDelegate>
@property (nonatomic, strong) NSArray *yearArr;
@property (nonatomic, strong) NSArray *monthArr;
@property (nonatomic, strong) NSArray *dayArr;
@property (weak, nonatomic) IBOutlet UIPickerView *picker;
@property (weak, nonatomic) IBOutlet UIButton *okButton;
@property (weak, nonatomic) IBOutlet UIView *popView;
@property (weak, nonatomic) IBOutlet UIView *indicatorView;
@property (weak, nonatomic) IBOutlet UIButton *CancelButton;
@property (weak, nonatomic) IBOutlet UILabel *titleDescriptionLabel;
@property (weak, nonatomic) IBOutlet UILabel *yearDescriptiionLabel;
@property (weak, nonatomic) IBOutlet UILabel *monthDescriptionLabel;
@property (weak, nonatomic) IBOutlet UILabel *dayDescriptionLabel;
@property (weak, nonatomic) IBOutlet UILabel *detailTitleLabel;
@end

@implementation BirthViewController

#pragma mark - View LifeCycle

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self configureLocalization];
    [self defaultSetting];
    [self addGestureRecognizer];
    [self updateThemeUI];
    [self registerNotification];
    
#if IsOEM
    self.detailTitleLabel.text = @"";
#endif
    
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
//    [MobClick beginLogPageView:@"BirthPage"];
    
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
//    [MobClick endLogPageView:@"BirthPage"];
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark - Notification

- (void)registerNotification
{
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateThemeUI) name:kThemeManagerChangeThemeNotification object:nil];
}

#pragma mark - Getter/Setter

- (NSArray *)yearArr
{
    if (_yearArr == nil) {
        NSMutableArray *years = [[NSMutableArray alloc] initWithCapacity:100];
        
        for (NSInteger index = kMaxYear - 100; index <= kMaxYear; index++) {
            [years addObject:[NSString stringWithFormat:@"%ld", (long)index]];
        }
        
        _yearArr = [years copy];
    }
    
    return _yearArr;
}

- (NSArray *)monthArr
{
    if (_monthArr == nil) {
        NSMutableArray *months = [[NSMutableArray alloc] initWithCapacity:12];
        for (NSInteger index = 1; index <= 12; index++) {
            [months addObject:[NSString stringWithFormat:@"%ld", (long)index]];
        }
        
        _monthArr = [months copy];
    }
    
    return _monthArr;
}

- (NSArray *)dayArr
{
    if (_dayArr == nil) {
        NSMutableArray *days = [@[] mutableCopy];
        for (NSInteger index = 1; index <= 31; index++) {
            [days addObject:[NSString stringWithFormat:@"%ld", (long)index]];
        }
        
        _dayArr = [days copy];
    }
    
    return _dayArr;
}

#pragma mark - IBAction

- (IBAction)cancel:(id)sender
{
    [self close];
}

- (IBAction)confirm:(id)sender
{
    if (self.delegate && [self.delegate respondsToSelector:@selector(birthViewController:didSelectBirth:)]) {
        
        NSInteger yearRowIndex = [self.picker selectedRowInComponent:kYearComponent];
        NSString *year = self.yearArr[yearRowIndex];
        NSAttributedString *attributeYear = [[NSAttributedString alloc] initWithString:year attributes:@{NSForegroundColorAttributeName:kOrangeColor}];

        NSInteger monthRowIndex = [self.picker selectedRowInComponent:kMonthComponent];
        NSString *month = self.monthArr[monthRowIndex];
        NSAttributedString *attributeMonth= [[NSAttributedString alloc] initWithString:month attributes:@{NSForegroundColorAttributeName:kOrangeColor}];

        NSInteger dayRowIndex = [self.picker selectedRowInComponent:kDayComponent];
        NSString *day = self.dayArr[dayRowIndex];
        NSAttributedString *attributeDay  = [[NSAttributedString alloc] initWithString:day attributes:@{NSForegroundColorAttributeName:kOrangeColor}];

        NSString *birth = [NSString stringWithFormat:@"%@-%@-%@", year, month, day];
        NSAttributedString *unitAttribute = [[NSAttributedString alloc] initWithString:@"-" attributes:@{NSForegroundColorAttributeName:[UIColor lightGrayColor]}];
        NSMutableAttributedString *attributeDate = [[NSMutableAttributedString alloc] initWithString:@""];
        [attributeDate appendAttributedString:attributeYear];
        [attributeDate appendAttributedString:unitAttribute];
        [attributeDate appendAttributedString:attributeMonth];
        [attributeDate appendAttributedString:unitAttribute];
        [attributeDate appendAttributedString:attributeDay];
        
        NSDate *birthDate = [NSDate formateYearMonthDayString:birth];
        
        if ([birthDate daysEarlierThan:[NSDate date]] > 0) {
            [self.delegate birthViewController:self didSelectBirth:attributeDate];
        } else {
            [self.delegate birthViewController:self didSelectBirth:[[NSAttributedString alloc] initWithString:[[NSDate date] formattedDateWithFormat:@"yyyy-MM-dd"]]];
        }
        
    }
    
    [self close];
}

#pragma mark - Private Method


- (void)configureLocalization{
    
    [self.okButton setTitle:NSLocalizedString(@"Ok", nil) forState:UIControlStateNormal];
    [self.CancelButton setTitle:NSLocalizedString(@"Cancel", nil) forState:UIControlStateNormal];
    self.titleDescriptionLabel.text = NSLocalizedString(@"Please choose birthday", nil);
    self.yearDescriptiionLabel.text = NSLocalizedStringFromTable(@"-", @"Location", nil);
    self.monthDescriptionLabel.text = NSLocalizedStringFromTable(@" - ", @"Location", nil);
    self.dayDescriptionLabel.text = NSLocalizedStringFromTable(@"  ", @"Location", nil);
    self.detailTitleLabel.text = NSLocalizedStringFromTable(@"Please enter correctly, we have birthday surprises for you. (Once you entered, cannot be changed in the future)", @"Location", nil);
}

- (void)updateThemeUI
{
//    self.okButton.backgroundColor = [[ThemeManager sharedInstance] pickerOkButtonColor];
//    self.popView.backgroundColor = [[ThemeManager sharedInstance] pickerBackgroundColor];
//    self.indicatorView.backgroundColor = [[ThemeManager sharedInstance] pickerSelectionIndicatorColor];
}

- (void)defaultSetting
{
    NSLog(@"date:%@", [NSDate formateYearMonthDayString:self.birth]);
    NSDate *birthDate = [NSDate formateYearMonthDayString:self.birth];
    NSInteger year = birthDate.year;
    NSInteger month = birthDate.month;
    NSInteger day = birthDate.day;
    
    NSString *yearStr = [NSString stringWithFormat:@"%ld", (long)year];
    NSString *monthStr = [NSString stringWithFormat:@"%ld", (long)month];
    NSString *dayStr = [NSString stringWithFormat:@"%ld", (long)day];
    
    [self.picker selectRow:[self.yearArr indexOfObject:yearStr] inComponent:kYearComponent animated:NO];
    [self.picker selectRow:[self.monthArr indexOfObject:monthStr] inComponent:kMonthComponent animated:NO];
    [self.picker selectRow:[self.dayArr indexOfObject:dayStr] inComponent:kDayComponent animated:NO];
}

- (void)close
{
    [self dismissFromParentViewControllerWithAnimationType:DetailViewControllerAnimationTypeSlide];
}

- (NSInteger)daysByYear:(NSString *)year month:(NSInteger)month
{
    if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) {
        return 31;
    } else if (month == 4 || month == 6 || month == 9 || month == 11) {
        return 30;
    } else {
        if (([year integerValue] % 4 == 0 && [year integerValue] % 100 != 0) || [year integerValue] % 400 == 0) {
            return 29;
        } else {
            return 28;
        }
    }
}

#pragma mark - UIPicker DataSource

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 3;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    if (component == kYearComponent) {
        return [self.yearArr count];
    } else if (component == kMonthComponent) {
        return [self.monthArr count];
    } else {
        
        NSInteger yearRowIndex = [pickerView selectedRowInComponent:kYearComponent];
        NSInteger monthRowIndex = [pickerView selectedRowInComponent:kMonthComponent];
        NSString *year = self.yearArr[yearRowIndex];
        
        return [self daysByYear:year month:monthRowIndex + 1];
    }
}

- (NSAttributedString *)pickerView:(UIPickerView *)pickerView attributedTitleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    NSString *rowStr = nil;
    if (component == kYearComponent) {
        rowStr = self.yearArr[row];
    } else if (component == kMonthComponent) {
        rowStr = self.monthArr[row];
    } else {
        rowStr = self.dayArr[row];
    }
    
    NSAttributedString *attribuedString = [[NSAttributedString alloc] initWithString:rowStr attributes:@{NSFontAttributeName: [UIFont systemFontOfSize:25.0f], NSForegroundColorAttributeName: [UIColor colorWithHex:0x7C7C7E]}];
    return attribuedString;
}

#pragma mark - UIPicker Delegate

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    if (component == kMonthComponent || component == kYearComponent) {
        NSInteger yearSelectedRow = [pickerView selectedRowInComponent:kYearComponent];
        NSInteger monthSelectedRow = [pickerView selectedRowInComponent:kMonthComponent];
        
        NSInteger daysRows = [pickerView numberOfRowsInComponent:kDayComponent];
        NSString *year = self.yearArr[yearSelectedRow];
        if (daysRows != [self daysByYear:year month:monthSelectedRow + 1]) {
            [pickerView reloadComponent:kDayComponent];
        }
    }
}

#pragma mark - Private Method

- (void)addGestureRecognizer
{
    UITapGestureRecognizer *gestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(close)];
    gestureRecognizer.cancelsTouchesInView = NO;
    gestureRecognizer.delegate = self;
    [self.view addGestureRecognizer:gestureRecognizer];
}
#pragma mark - UIGestureRecognizerDelegate

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
    return self.view == touch.view;
}

@end
